package com.yuntsg.nnsfcp.service.front.ut;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * unicode 工具类
 *
 * @author ：ljx
 * @date ：Created in 2019/8/4
 */
public class UniCodeUtil {

    /**
     * 解析 unicode 码
     */
    private static final Pattern PATTERN = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

    /**
     * 中文 转  unicode
     *
     * @param string
     * @return
     */
    public static String eCode(String string) {
        char[] chars = string.toCharArray();
        StringBuilder strBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (PinYinUtil.isChinese(String.valueOf(chars[i]))) {
                strBuilder.append("\\u").append(Integer.toString(chars[i], 16));
            } else {
                strBuilder.append(chars[i]);
            }
        }
        return strBuilder.toString();
    }

    /**
     * unicode  转  中文
     *
     * @param string
     * @return
     */
    public static String dCode(String string) {
        Matcher matcher = PATTERN.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }
}
